package wu.seal.utils

import java.io.File
import java.util.*


fun String.isPhoneLogCommend(): Boolean {
    return "(-pt|-pd|-ptd|-pdd|-pte|-pted|-ptest)".toRegex().matches(this)
}

/**
 * 复制手机上的相应日志文件到目标本地文件夹中
 */
fun copyPhoneLog(phoneLogCommend: String, localDirPath: String) {
    val phoneLogDir = when (phoneLogCommend) {
        "-pt" -> "/sdcard/Android/data/me.talkyou.app.im/files/log/"
        "-pd" -> "/sdcard/Android/data/me.dingtone.app.im/files/log/"
        "-ptd" -> "/sdcard/Android/data/me.talkyou.app.im.debug/files/log/"
        "-pdd" -> "/sdcard/Android/data/me.dingtone.app.im.debug/files/log/"
        "-pte" -> "/sdcard/Telos/log/"
        "-pted" -> "/sdcard/TelosDebug/log/"
        "-ptest" -> "/sdcard/Android/data/me.dt.im.cppmodule.app.talkyou/files/log/"
        else -> throw IllegalArgumentException("传入的第一个参数不合规，应该是-pt|-pd|-ptd|-pdd|-pte|-pted 中的一个现在是$phoneLogCommend")
    }

    if (File(localDirPath).exists().not()) {
        throw IllegalStateException("要复制到的目录文件夹不存在！")
    }
    val process = Runtime.getRuntime().exec(arrayOf("adb", "pull", phoneLogDir, localDirPath))
    platformPrint(process.errorStream.reader().readText())
    platformPrint(process.inputStream.reader().readText())
    process.destroy()
}

fun obtainNewLogFile(cmdArgs: Array<String>): File {
    val newFileName = obtainLogFileName(cmdArgs)
    platformPrint("create new cache log file name is $newFileName")
    return File(obtainDtLogDir(), newFileName).apply {
        createNewFile()
    }
}

private fun obtainDtLogDir(): File {
    val useDirPath = System.getProperty("user.home")

    val cal = Calendar.getInstance()
    val year = cal.get(Calendar.YEAR)
    val month = cal.get(Calendar.MONTH)
    val day = cal.get(Calendar.DATE)
    val logDirPath = "$useDirPath/DTLog/$year-$month-$day"
    val logDirFile = File(logDirPath)
    logDirFile.mkdirs()

    return logDirFile
}

private fun obtainLogFileName(cmdArgs: Array<String>): String {

    return cmdArgs.joinToString("-").replace("/", "-").replace(":", "-").prependIndent("DT_") + "-${System.currentTimeMillis()}.log"
}

fun nowInMacRuntime(): Boolean {
    return System.getProperty("os.name").startsWith("Mac OS")
}

fun nowInWindowsRuntime(): Boolean {
    return System.getProperty("os.name").startsWith("Windows")
}

fun String.toGBKString(): String {
    return toByteArray(charset("utf-8")).toString(charset("GBK"))
}

/**
 * 兼容windows平台的字符串输出,避免乱码
 */
fun platformPrint(s: String) {
    println(if (nowInWindowsRuntime()) s.toGBKString() else s)
}
